# -*- coding: utf-8 -*-
"""
手机屏幕截图的代码
"""
import subprocess
import os
import sys
import datetime
import cv2
import time

try:
    from common.auto_adb import auto_adb
except Exception as ex:
    print(ex)
    print('请将脚本放在项目根目录中运行')
    print('请检查项目根目录中的 common 文件夹是否存在')
    exit(1)
adb = auto_adb()
# SCREENSHOT_WAY 是截图方法，经过 check_screenshot 后，会自动递减，不需手动修改
SCREENSHOT_WAY = 3
file_name = 'current.png'
file_path = './temp/{}'.format(file_name)

def pull_screenshot2():
    """
    获取屏幕截图，目前有 0 1 2 3 四种方法，未来添加新的平台监测方法时，
    可根据效率及适用性由高到低排序
    """
    global SCREENSHOT_WAY
    if 1 <= SCREENSHOT_WAY <= 3:
        process = subprocess.Popen(
            adb.adb_path + ' shell screencap -p',
            shell=True, stdout=subprocess.PIPE)
        binary_screenshot = process.stdout.read()
        if SCREENSHOT_WAY == 2:
            binary_screenshot = binary_screenshot.replace(b'\r\n', b'\n')
        elif SCREENSHOT_WAY == 1:
            binary_screenshot = binary_screenshot.replace(b'\r\r\n', b'\n')
        print(os.path.abspath(file_path))
        fh = open(os.path.abspath(file_path), 'w', encoding='utf-8')
        fh.write(binary_screenshot)
        fh.close()
        return cv2.imread(file_path)
    elif SCREENSHOT_WAY == 0:
        if os.path.isfile(file_path):
            try:
                filename = file_path.replace(file_name, datetime.datetime.now().strftime("%H%M%S") + '.png')
                os.system('mv {0} {1}'.format(file_path, filename))  # 把就图片改为时间命名的文件作为历史记录
            except Exception:
                pass
        adb.run('shell screencap -p /sdcard/current.png')  # 截图
        adb.run('pull /sdcard/current.png {}'.format(file_path))  # 保存到本地
        return cv2.imread(file_path)


def pull_screenshot():
    try:
        filename = file_path.replace(file_name, datetime.datetime.now().strftime("%H%M%S") + '.png')
        os.system('mv {0} {1}'.format(file_path, filename))  # 把就图片改为时间命名的文件作为历史记录
    except Exception:
        pass
    adb.run('shell screencap -p /sdcard/current.png')  # 截图
    time.sleep(2)
    adb.run('pull /sdcard/current.png {}'.format(file_path))  # 保存到本地
    time.sleep(2)
    return cv2.imread(file_path)


def check_screenshot():
    """
    检查获取截图的方式
    """
    global SCREENSHOT_WAY
    if SCREENSHOT_WAY < 0:
        print('暂不支持当前设备')
        sys.exit()
    try:
        print('采用方式 {} 获取截图'.format(SCREENSHOT_WAY))
        im = pull_screenshot()
    except Exception:
        SCREENSHOT_WAY -= 1
        check_screenshot()
